import columnOptions from '@/util/columns-config'
import { getToken } from '@/util/auth'
import quickModal from '@yizhai/quick-el-modal'
import { Base64 } from 'js-base64'
import { Notification } from 'element-ui'
import website from '@/config/website'
import i18n from '@/lang'
import axios from '@/router/axios'
import * as config from '@/config/env'
import BasicBlock from '@/components/base/basic-block'
import BasicContainer from '@/components/base/basic-container'
import ThirdRegister from '@/components/base/third-register'
import Suppliers from '@/components/supplier/suppliers'
import Materials from '@/components/supplier/materials'
import MaterialsCategory from '@/components/supplier/materials-category'
import Leading from '@/components/business/leading-cadre'
import TopNotice from '@/components/base/top-notice'
import Tags from '@/components/base/tags'
import TopSearch from '@/components/base/top-search'
import WfCustomFields from '@/views/plugin/workflow/components'
import TenantPackage from '@/views/system/tenant-package'
import AvueUeditor from 'avue-plugin-ueditor'
// import QuickDrawer from '@yizhai/quick-el-drawer'
import QuickDrawer from '@/views/plugin/workflow/components/quickDrawer/index'
import QuickModal from '@yizhai/quick-el-modal'
import EasyUpload from '@yizhai/easy-upload'
import ProLayout from '@iamgx/pro-layout'
import loadStyle from '@iamgx/load-style'
import Descriptions from 'element-ui/lib/descriptions'
import Result from 'element-ui/lib/result'
import DescriptionsItem from 'element-ui/lib/descriptions-item'
import { validateFileList } from '@/util/validate'
import store from '@/store/index'
export const i18nFormat = (key, value) => i18n.t(key, value)

const onImagePreview = file => {
  const src = file.link
  // const src = file?.response?.data?.link
  // console.log(src)
  if (!src || !src.endsWith('g')) return
  quickModal({
    width: '440px',
    buttons: [{ text: '下载', callback: () => window.open(src, '_blank') }],
    component(h) {
      return h('img', { style: 'width: 400px;height: 400px;object-fit: contain;', attrs: { src } })
    }
  })
}

const fileBeforeUpload = (file, { accept = '', size }) => {
  if (accept) {
    const isAccept = accept.includes(file.name.split('.')[1])
    if (!isAccept) {
      Notification.warning({ message: `只能上传 ${accept} 格式!` })
      return false
    }
  }

  if (file.size / 1024 / 1024 > Number(size)) {
    Notification.warning({ message: `图片大小为${file.size / 1024 / 1024}MB, 不能超过 ${size}MB!` })
    return false
  }
  return true
}

export default {
  install(Vue) {
    if (this.installed) return

    Vue.use(window.AVUE, {
      size: 'small',
      axios,
      tableSize: 'small',
      calcHeight: 65,
      columnOptions,
      i18n: i18nFormat
    })
      .use(WfCustomFields) // 表单设计器业务组件
      .use(window.AvueFormDesign)
      .use(window.WfDesign.default)
      .use(ProLayout)
      .use(Descriptions)
      .use(DescriptionsItem)
      .use(Result)
      .use(EasyUpload, {
        drag: true,
        i18n: i18nFormat,
        action: config.uploadUrl,
        onPreview: onImagePreview,
        beforeUpload: fileBeforeUpload,
        headers: (() => ({
          [website.tokenHeader]: 'bearer ' + getToken(),
          Authorization: `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`
        }))()
      })

    // 将 components/business 下的所有组件注册为全局组件
    const requireComponent = require.context('../components/', true, /\.vue$/)
    requireComponent.keys().forEach(name => {
      const config = requireComponent(name)
      Vue.component(config.default.name, config.default || config)
    })

    Vue.component('basic-container', BasicContainer)
    Vue.component('basic-block', BasicBlock)
    Vue.component('third-register', ThirdRegister)
    Vue.component('avue-ueditor', AvueUeditor)
    Vue.component('tenant-package', TenantPackage)
    Vue.component('top-notice', TopNotice)
    Vue.component('tags', Tags)
    Vue.component('top-search', TopSearch)
    Vue.component(Suppliers.name, Suppliers)
    Vue.component('leading', Leading)
    Vue.component(Materials.name, Materials)
    Vue.component(MaterialsCategory.name, MaterialsCategory)
    Vue.component('custom-image', {
      props: ['src'],
      render(h) {
        const { $props: props, src, $attrs: attrs, $listeners: on } = this
        return h('img', { props, attrs: { src: this.ASSETS_CDN + src, ...attrs }, on })
      }
    })

    Vue.prototype.$quickDrawer = QuickDrawer
    Vue.prototype.$quickModal = QuickModal
    Vue.prototype.website = website
    Vue.prototype.emitter = new Vue()
    Vue.prototype.validateFileList = validateFileList

    // 加载 CONFIG URL
    Object.keys(config).forEach(key => (Vue.prototype[key] = config[key]))

    // 动态加载阿里云字体库
    config.iconfontVersion.forEach(ele => {
      loadStyle(config.iconfontUrl.replace('$key', ele))
    })
  }
}
